package com.central.apps.handler;

import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class ScrapassetAppHandler extends LvBaseHandler {

    @Autowired
    private HandlerService handlerService;

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if(flowNode.getId().equals("spr")){
            //获取子表资产编号
            String getSonNumSql ="select assetnum from bl_scrapline where scrapnum =(select scrapnum from bl_scrapasset where id="+id+")";
            List<Map<String, Object>> bySql = handlerService.findBySql(getSonNumSql);
            Map<String, Object> map =new HashMap<>();
            for(int i =0;i<bySql.size();i++){
                String assetnum = (String) bySql.get(i).get("assetnum");
                //更新资产台账状态为报废
                String updSql ="update bl_asset set status ='报废' where assetnum ='"+assetnum+"';";
                handlerService.updateBySql(updSql);
            }
        }
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
            log.info("开始计算++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            String scrapnum = MapUtils.getString(data, "scrapnum");
            //获取子表设备资产净值求和
            String Sql ="select assetvalue from bl_scrapline where scrapnum ='"+scrapnum+"';";
            List<Map<String, Object>> sumSonInfosbySql = handlerService.findBySql(Sql);
            Map<String, Object> map=new HashMap<>();
            double assetvalue = 0;
            for(int i=0;i<sumSonInfosbySql.size();i++){
                map=sumSonInfosbySql.get(i);
                assetvalue = (double)map.get("assetvalue")+assetvalue;
            }
            //获取子表数据条数更新到主表报废资产数量字段quantity
            String quantity =Integer.toString(sumSonInfosbySql.size());
            //更新到主表
            String updSql ="update bl_scrapasset set quantity ='"+quantity+"',"+"currentvalue= "+assetvalue +"where scrapnum ='"+scrapnum+"';";
            handlerService.updateBySql(updSql);
    }
}
